<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Establecimientos SMS</h3>
  </div>
  <div class="panel-body">
  	<div id="custom-toolbar">
        <div class="form-inline" role="form">
        	<label class="control-label">Sin Equivalencias</label>
            <input type="checkbox" id="sinEquiv" name="sinEquiv" checked="checked">
            <input type="button" value="Agregar" id="agregar" class="btn btn-default">
        </div>
    </div>
    <table id="table" data-search="true" data-toolbar="#custom-toolbar"
		data-side-pagination="server" data-pagination="true"
		data-page-list="[10, 20, 30]"
		data-url="<?php echo base_url();?>index.php/establecimientoEquiv/lista">
      <thead>
        <tr>
          <th data-field="ID_ESTABLECIMIENTOS_EQUIV" data-align="center" data-sortable="false">ID</th>
          <th data-field="BANCO" data-align="center" data-sortable="false">BANCO</th>
          <th data-field="EQUIVALENCIA" data-align="center" data-sortable="false">NOMBRE</th>
          <th data-field="ESTABLECIMIENTO" data-align="center" data-sortable="false">ESTABLECIMIENTO</th>
          <th data-field="ID_ESTABLECIMIENTOS_EQUIV" data-width="90" data-align="center" data-sortable="false" 
              data-formatter="formatButton"></th>
        </tr>
      </thead>
    </table>
  </div>
</div>

<div id="dialogEquiv" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 id="lblTitulo" class="modal-title">Seleccionar Establecimiento</h4>
			</div>
			<form id="formAsignar" class="form-horizontal" method="post" 
					action="<?php echo base_url();?>index.php/establecimientoEquiv/asignar">
				<div class="modal-body">
					<div class="form-group">
						<input type="hidden" id="equivalencia" name="equivalencia">
						<label class="col-sm-2 control-label">Establecimiento</label>
						<div class="col-sm-10">
							<select id="establecimiento" name="establecimiento" style="width: 100%" class="selectpicker with-ajax"
								data-live-search="true">
							</select>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="submit" class="btn btn-default">Aceptar</button>
				</div>
			</form>
		</div>
		<!-- /.modal-content -->
	</div>
	<!-- /.modal-dialog -->
</div>

<div id="dialogAgregar" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 id="lblTitulo" class="modal-title">Agregar Item</h4>
			</div>
			<form id="formAgregar" class="form-horizontal" method="post" 
					action="<?php echo base_url();?>index.php/establecimientoEquiv/guardar">
				<div class="modal-body">
					<div class="form-group">
						<input type="hidden" id="estabEquiv" name="estabEquiv">
						<label class="col-sm-3 control-label">Banco</label>
						<div class="col-sm-9">
						  <select id="idBanco" name="idBanco" required>
						  	<option value=""></option>
						  	<?php foreach ($bancos as $banco):?>
							<option value="<?php echo $banco->ID_BANCO;?>"><?php echo $banco->NOMBRE;?></option>
							<?php endforeach;?>
						  </select>
						</div>
					</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">Nombre</label>
							<div class="col-sm-6">
								<input id="nombre" name="nombre" type="text" required>
							</div>
							<label class="col-sm-2 control-label">Es expr.</label>
							<div class="col-sm-1">
								<input id="expresion" name="expresion" type="checkbox">
							</div>
						</div>
						<div class="form-group" id="panelExpr" style="display: none;">
							<label class="col-sm-3 control-label">Expresion</label>
							<div class="col-sm-5">
								<input id="txtPrueba" name="txtPrueba" type="text">
							</div>
							<div class="col-sm-2" id="estadoExpr"></div>
							<div class="col-sm-2">
								<button type="button" id="btnTest" class="btn btn-default">Test</button>
							</div>
						</div>
						<div class="form-group">
							<input type="hidden" id="establ" name="establ">
							<label class="col-sm-3 control-label">Establecimiento</label>
							<span class="col-sm-4" id="txtEstabl"></span>
							<div class="col-sm-5">
								<input id="busEst" placeholder="Buscar establecimiento">
							</div>
						</div>
				</div>
				<div class="modal-footer">
					<button type="submit" class="btn btn-default">Aceptar</button>
				</div>
			</form>
		</div>
	</div>
</div>

<script type="text/javascript">
	$(function() {
		$('#table').bootstrapTable({
	  		cache: false,
	  		queryParams: function (p) {
		  		p.sinEquiv = $("#sinEquiv").is(":checked");
		  		return p;
	  		}
		});

		$("#sinEquiv").click (function() {
			$('#table').bootstrapTable('refresh', {silent: true});
		});

		$('#establecimiento').selectpicker().filter('.with-ajax').ajaxSelectPicker({
	        ajax: {
	            url: '<?php echo base_url();?>index.php/establecimientoEquiv/establecimientos',
	            type: 'POST',
	            dataType: 'json',
	            data: {palabra: '{{{q}}}',items: 5}
	        },
	        cache: false,
	        preserveSelected: false,
	        preprocessData: function (data) {
	            var i, l = data.length, array = [];
	            if (l) {
	                for(i = 0; i < l; i++){
	                    array.push($.extend(true, data[i], {
	                        text: data[i].NOMBRE,
	                        value: data[i].ID_ESTABLECIMIENTO,
	                    }));
	                }
	            }
	            return array;
	        }
	    });

		$('#formAsignar').ajaxForm({
			success: function (response, statusText) {
		        $('#dialogEquiv').modal('hide');
		        $('#table').bootstrapTable('refresh', {silent: true});
		        BootstrapDialog.alert('Asignacion guardada');
		    }
	    });

		$('#formAgregar').ajaxForm({
			beforeSubmit: function(arr, $form, options) {
	    		var est = $('#establ').val();
	    		if (est == null || est == '') {
	        		alert ("Seleccione un establecimiento");
	        		return false;
	    		}
	    		return true;
	    	},
			success: function (response, statusText) {
		        $('#dialogAgregar').modal('hide');
		        $('#table').bootstrapTable('refresh', {silent: true});
		        BootstrapDialog.alert('Guardado');
		    }
	    });
	    
	    $("#busEst").autocomplete({
	    	source: function( request, response ) {
	            $.ajax({
	              url: "<?php echo base_url();?>index.php/establecimientoEquiv/listaEstablecimientos",
	              type: 'POST',
	              data: {
	            	  palabra: request.term,
	            	  items: 5
	              },
	              success: function( data ) {
	                var arr = [];
	            	$.each(data, function( index, value ) {
	            		arr.push({id: value.id, label: value.no, value: value.no});
	            	});
	                response( arr );
	              }
	            });
	          },
	        minLength: 2,
	        select: function( event, ui ) {
	            $("#txtEstabl").text(ui.item.value);
	            $("#establ").val(ui.item.id);
	            $(this).val('');
	            return false;
	        }
	    });

	    $("#expresion").click(function() {
	    	if ($(this).is(':checked')) {
	    		$("#panelExpr").show();
	    	} else {
	    		$("#panelExpr").hide();
	    	}
		});

		$("#agregar").click(function() {
			$('#dialogAgregar').modal('show');
		});

		$("#btnTest").click(function() {
			var nombre = $("#nombre").val();
			var txtPrueba = $("#txtPrueba").val();
			
            $.ajax({
	              url: "<?php echo base_url();?>index.php/establecimientoEquiv/validarExpresion",
	              type: 'POST',
	              data: {
	            	  expr: nombre,
	            	  text: txtPrueba
	              },
	              success: function( data ) {
	                if (data == 1) {
		                $("#estadoExpr").text("Correcto");
	                } else {
	                	$("#estadoExpr").text("Incorrecto");
	                }
	              }
	       	});
		});
	});

	function formatButton (value, row) {
		return '<button class="btn btn-default btn-xs" type="button" onclick="asignar(' + value + ')">Asignar</button>';
	}

	function asignar (value) {
		$('#equivalencia').val(value);
		$('#dialogEquiv').modal('show');
	}
</script>